<?php
  /**
  * //////////////////////////////////////////////////
  * auto execute , for initialize config variable
  * this function auto call every page has been fetch
  */
  function VoteAlert_permission() {
    // Security check
    //we are allow for admin access level , see in config.php variable name ACCESS_ADMIN
    if (!SecurityUtil::checkPermission('VoteAlert::', '::', ACCESS_NONE)) {
        LogUtil::registerPermissionError(pnModUrl('Users','user','loginscreen'));
    }
  }

  /**
  * smarty template auto call before render
  */
  function _languageRender(&$render){

    Loader::loadClass('LanguageUtil');
    $languages = LanguageUtil::getLanguages();
    $currentLanguage = pnUserGetLang();
    $render->assign('languages', $languages);
    $render->assign('currentLanguage', $currentLanguage);
    
  }

  /**
  * Main user function, simply return the index page.
  * @author Parinya Bumrungchoo
  * @return string HTML string
  */
  function VoteAlert_user_main() {
    return VoteAlert_user_cron();
  }

  /**
  * cron job, compute vote data and match between user and voting data.
  * @author Thapakorn Tantirattanapong
  */
  function VoteAlert_user_cron() {
    
    //$ctrl the class name
    $ctrl    = FormUtil::getPassedValue ('ctrl', 'cron' , 'GET');
    //$method the method of request for edit or view enum[ view | form | delete | list | page]
    $func  = FormUtil::getPassedValue ('func', 'page' , 'GET');
    $render = pnRender::getInstance('VoteAlert');
    
    $_start = microtime();
    
    $pnTable = pnDBGetTables();
    
    $tableUsers = $pnTable['users'];
    $columnUsers = $pnTable['users_column'];
    

    $tableVoteData = $pnTable['votealert_votedata'];
    $columnVoteData = $pnTable['votealert_votedata_column'];
    
    $tableVoteType = $pnTable['votealert_votetype'];
    $columnVoteType = $pnTable['votealert_votetype_column'];
    
    $query = "SELECT 
                $columnVoteData[id],
                $columnVoteData[title],
                $columnVoteData[province_id],
                $columnVoteData[district_id],
                $columnVoteData[tambon_id],
                $columnVoteData[date],
                $columnVoteData[lat],
                $columnVoteData[lon],
                $columnVoteData[votetype_id],
                $columnVoteData[president],
                $columnVoteData[amount_member],
                $columnVoteData[comment],
                $columnVoteType[name],
                $columnVoteType[group]
              FROM 
                $tableVoteData,
                $tableVoteType
              WHERE 
                ($columnVoteData[date] = DATE_ADD(CURDATE(), INTERVAL 1 DAY))
              AND 
                $columnVoteData[votetype_id] = $columnVoteType[id]";

    $column = array("id",
                    "title",
                    "province_id",
                    "district_id",
                    "tambon_id",
                    "date",
                    "lat",
                    "lon",
                    "votetype_id",
                    "president",
                    "amonut_member",
                    "comment",
                    "votetype",
                    "group"
                    );
    $result = DBUtil::executeSQL($query);
    $objectArray = DBUtil::marshallObjects ($result, $column);

    foreach($objectArray as $value)
    {
      if(intval($value['group'])&&$value['group']>0)
      {
        
        if(true)
        {
                 
          $tableUserProperty = $pnTable['user_property'];
          $columnUserProperty = $pnTable['user_property_column'];
          $tableUserData = $pnTable['user_data'];
          $columnUserData = $pnTable['user_data_column'];
          
          switch($value['group'])
          {
            case 1: //country case
                    $value['group'] = "country";
                    break;
            case 2: //Province case
                    $query = "SELECT
                                $columnUserData[uda_uid]
                              FROM
                                $tableUserProperty,$tableUserData
                              WHERE
                                $columnUserProperty[prop_label] = 'province'
                              AND
                                $columnUserData[uda_propid] = $columnUserProperty[prop_id] 
                              AND
                                $columnUserData[uda_value] = ".$value['province_id'];
                                
                                $value['group'] = "province";
                    
                    break;
            case 3: //district case
                    $query = "SELECT
                                $columnUserData[uda_uid]
                              FROM
                                $tableUserProperty,$tableUserData
                              WHERE
                                $columnUserProperty[prop_label] = 'district'
                              AND
                                $columnUserData[uda_propid] = $columnUserProperty[prop_id] 
                              AND
                                $columnUserData[uda_value] = ".$value['district_id'];
                                
                                $value['group'] = "district";
                    break;
            case 4: //tambon case
                    $query = "SELECT
                                $columnUserData[uda_uid]
                              FROM
                                $tableUserProperty,$tableUserData
                              WHERE
                                $columnUserProperty[prop_label] = 'tambon'
                              AND
                                $columnUserData[uda_propid] = $columnUserProperty[prop_id] 
                              AND
                                $columnUserData[uda_value] = ".$value['tambon_id'];
                                
                                $value['group'] = "tambon";
                    break;
                    
            default:
          }
        }else{
          $tableObjectdataAttributes = $pnTable['objectdata_attributes'];
          $columnObjectdataAttributes = $pnTable['objectdata_attributes_column'];  
          switch($value['group'])
          {
            case 1: //country case
                    $value['group'] = "country";
                    break;
            case 2: //Province case
                    $query = "SELECT
                                $columnObjectdataAttributes[object_id]
                              FROM
                                $tableObjectdataAttributes
                              WHERE
                                $columnObjectdataAttributes[attribute_name] = 'province' 
                              AND
                                $columnObjectdataAttributes[value] = ".$value['province_id'];
                                $value['group'] = "province";
                    
                    break;
            case 3: //district case
                    $query = "SELECT
                                $columnObjectdataAttributes[object_id]
                              FROM
                                $tableObjectdataAttributes
                              WHERE
                                $columnObjectdataAttributes[attribute_name] = 'district' 
                              AND
                                $columnObjectdataAttributes[value] = ".$value['district_id'];
                                $value['group'] = "district";
                    break;
            case 4: //tambon case
                    $query = "SELECT 
                                $columnObjectdataAttributes[object_id]
                              FROM 
                                $tableObjectdataAttributes
                              WHERE 
                                $columnObjectdataAttributes[attribute_name] = 'tambon' 
                              AND 
                                $columnObjectdataAttributes[value] = ".$value['tambon_id'];
                                $value['group'] = "tambon";
                    break;
                    
            default:
          }
        }
        
        $column = array("id");
        $result = DBUtil::executeSQL($query);
        $userArray[$value['id']] = DBUtil::marshallObjects ($result, $column);
        $column = array("email","uname");
        $i=0;
        foreach($userArray[$value['id']] as $user)
        {
          $query = "SELECT
                      $columnUsers[email],$columnUsers[uname]
                    FROM
                      $tableUsers
                    WHERE
                      $columnUsers[uid] = ".$user['id'];
                    
          
          $result = DBUtil::executeSQL($query);
          $userDetail = DBUtil::marshallObjects ($result, $column);
          $list[$value['id']]['user'][$i]['id'] = $user['id'];

          foreach($userDetail[0] as $key=>$val)
          {
             $list[$value['id']]['user'][$i][$key] = $val;
          }
          $list[$value['id']]['votedata'] = $value;
          $i++;
        }
        
        _NotifyUser($list[$value['id']]['user'],$list[$value['id']]['votedata']);
        
      }
    }
    
    //$message = "Took ".number_format(_DiffMicrotime($_start,microtime()), 4)." seconds to execute\n";
    //$render->assign('usedtime',$message);
    //return $render->fetch('user_'.$func.'_'.strtolower($ctrl).'.htm');
    pnShutDown();
  }
  
  function _DiffMicrotime($mt_old,$mt_new)
  {
    list($old_usec, $old_sec) = explode(' ',$mt_old);
    list($new_usec, $new_sec) = explode(' ',$mt_new);
    $old_mt = ((float)$old_usec + (float)$old_sec);
    $new_mt = ((float)$new_usec + (float)$new_sec);
    return $new_mt - $old_mt;
  }
  
  function _NotifyUser($userlist,$votedata)
  {
    foreach($userlist as $user)
    {
      /* send notify e-mail */
      $adminmail = pnConfigGetVar('adminmail');
      $sitename = pnConfigGetVar('sitename');
      $notifytime = date("m/j/Y g:ia" );
      
      $headers .= "From: $sitename Notifier Tools $adminmail\n";
      $headers .= "X-Sender: <$sitename>\n";
      $headers .= "X-Mailer: PHP E-mail Notifier by Thapakorn Tantirattanapong\n";
      $headers .= "X-Mailer-Version: ".PN_VERSION_ID." ".PN_VERSION_NUM."\n";
      $headers .= "X-Priority: 1\n";
      $headers .= "Get-Script-At: <http://www.zikula.org>\n";
      
      $subject = "You have election event.";
      $body = $user['uname']."[".$user['id']."], You have election event. more detail: \n\n";
      foreach($votedata as $key=>$val)
      {
        $body .= $key."=>".$val."\n";
      }
      $body .= "\n\n\nNotify at ".$notifytime;
      
      
      //var_dump($user);
      //var_dump($votedata);
      echo "Sent : ".$user['email']."<br>";
      
      // Send the mail message.
      
      if(!pnMail($user['email'], $subject, $body, '', 0, 1))
      {
        return LogUtil::registerError('Error! Can\'t Send Notification E-mail.');
      }
      //pnMail($to, $subject, $message = '', $headers = '', $html = 0, $debug = 0)
    }
    
    return true;

  }
?>